import Vue from 'vue'
import * as dayjs from 'dayjs'
import { getDictItemsValue } from '@/api/api'

Vue.filter('NumberFormat', function (num) {
  if (!num) {
    num = 0
  }
  return (num.toString().indexOf('.') !== -1) ? num.toLocaleString() : num.toString().replace(/(\d)(?=(\d{3})+$)/g, '$1,')
  // return (value+ '').replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g,'$1,');
  // let intPartFormat = value.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') //将整数部分逢三一断
  // return intPartFormat
})

Vue.filter('NumberFormatAndFixed', function (num, fixed) {
  if (!num) {
    num = 0
  }
  num = num.toFixed(fixed)
  // return num.toString().replace(/(\d)(?=(\d{3})+$)/g, '$1,');
  return (num + '').replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,')
  // let intPartFormat = value.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') //将整数部分逢三一断
  // return intPartFormat
})
// var fun1 = async function(){
//   await axios.get(url,params);
//
// ...
// }

Vue.filter('dictText', function (val, code) {
  let text = ''

  if (val && code) {
    // await
    text = getDictItemsValue({ dictCode: code, key: val }).then((res) => {
      if (res.success) {
        return res.result
      }
    })
  }
  return text
})

Vue.filter('dayjs', function (dataStr, pattern = 'YYYY-MM-DD HH:mm:ss') {
  return dayjs(dataStr).format(pattern)
})

Vue.filter('day', function (dataStr, pattern = 'YYYY-MM-DD') {
  if (!dataStr) {
    return ''
  }
  return dayjs(dataStr).format(pattern)
})

Vue.filter('money', function (dataStr) {
  if (!dataStr) {
    dataStr = 0
  }
  return dataStr.toLocaleString('zh-Hans-CN', { style: 'currency', currency: 'CNY' })
})

/** 字符串超长截取省略号显示 */
Vue.filter('ellipsis', function (value, vlength = 25) {
  if (!value) {
    return ''
  }
  console.log('vlength: ' + vlength)
  if (value.length > vlength) {
    return value.slice(0, vlength) + '...'
  }
  return value
})